package lewiszlw.sso.server.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.ir.annotations.Reference;
import lewiszlw.sso.server.entity.PartnerEntity;
import lewiszlw.sso.server.entity.PartnerProductEntity;
import lewiszlw.sso.server.entity.ShipmentEntity;
import lewiszlw.sso.server.mapper.PartnerMapper;
import lewiszlw.sso.server.mapper.PartnerProductMapper;
import lewiszlw.sso.server.mapper.ShipmentMapper;
import lewiszlw.sso.server.service.ShipmentService;
import lewiszlw.sso.server.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/demo")
public class DemoCintroller {
    @Reference
    private ShipmentService shipmentService;
    @Autowired
    private ShipmentMapper shipmentMapper;
    @Autowired
    private PartnerProductMapper productMapper;
    @Autowired
    private PartnerMapper partnerMapper;

    @RequestMapping("/auth")
    public void auth() {
//        shipmentService.sendShipmentMethod(1,1);
        String body = "";
        try {
            CommonUtil commonUtil = new CommonUtil();
            List<String> params = new ArrayList<>();
            String token = "7s2h3843hjj290726khsnn782ns0s76ss";
            String timestamp = String.valueOf(System.currentTimeMillis());
            String eventId = "234567";
            params.add(eventId);
            params.add(timestamp);
            params.add(token);
            Collections.sort(params);
            String localSignature = StringUtils.join(params, "");
            String signature = commonUtil.sha256(localSignature);
            String shipmentUrl = "http://api.nanofintax.com/channel/api/partner?signature=" + signature + "&timestamp=" + timestamp + "&eventId=" + eventId;
            ShipmentEntity shipmentEntity = shipmentMapper.queryShipmentById(1);
//            shipmentEntity.setRequestId("");//随机
//            shipmentEntity.setOrderId("");//goodId
//            shipmentEntity.setAccountId("");//userName
//            shipmentEntity.setOpenId("");//userID
//            shipmentEntity.setProductId("");//goodId
//            shipmentEntity.setSkuId("");//classify_num


            PartnerProductEntity partnerProductEntity = productMapper.queryPartnerProductById(1);
            shipmentEntity.setPartnerProductInfo(partnerProductEntity);
            JSONObject json = (JSONObject) JSONObject.toJSON(shipmentEntity);
            System.out.println(json);
            body = send(shipmentUrl, json, "UTF-8");
            System.out.println("有度税智发货接口返回数据:" + body);
        } catch (Exception e) {
            e.getMessage();
        }
    }

    @RequestMapping("/openPartner")
    public void openPartner() {
        String body = "";
        try {
            CommonUtil commonUtil = new CommonUtil();
            List<String> params = new ArrayList<>();
            String token = "7s2h3843hjj290726khsnn782ns0s76ss";
            String timestamp = String.valueOf(System.currentTimeMillis());
            String eventId = "234567";
            params.add(eventId);
            params.add(timestamp);
            params.add(token);
            Collections.sort(params);
            String localSignature = StringUtils.join(params, "");
            String signature = commonUtil.sha256(localSignature);
            String shipmentUrl = "http://api.nanofintax.com/channel/api/partner/open?signature=" + signature + "&timestamp=" + timestamp + "&eventId=" + eventId;
            PartnerEntity partnerEntity = partnerMapper.queryPartnerById(1);
            JSONObject json = (JSONObject) JSONObject.toJSON(partnerEntity);
            System.out.println("传输json数据:" + json);
            body = send(shipmentUrl, json, "UTF-8");
            System.out.println("有度税智发货接口返回数据:" + body);
        } catch (Exception e) {
            e.getMessage();
        }
    }

    /**
     * 发送post请求
     * @param url  路径
     * @param jsonObject  参数(json类型)
     * @param encoding 编码格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String send(String url, JSONObject jsonObject, String encoding) throws ParseException, IOException {
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader("utf-8","application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        System.out.println("请求地址："+url);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
//        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

}
